﻿#include "Listn.h"
ListNode* ListBuyNode(LTDataType x)
{
	ListNode* Newnode = malloc(sizeof(ListNode));
	if (Newnode == NULL)
	{
		perror("ListBuyNode::malloc");
		exit(1);
	}
	Newnode->_data = x;
	Newnode->_next = Newnode->_prev = Newnode;
	return Newnode;
}



ListNode* ListCreate()
{
	ListNode* head = ListBuyNode(-1);
	return head;
}



void ListPushBack(ListNode* pHead, LTDataType x)
{
	assert(pHead);

	ListNode* newnode = ListBuyNode(x);
	ListNode* pcur = pHead;
	while (pcur->_next != pHead)
	{
		pcur = pcur->_next;
	}
	pcur->_next = newnode;
	newnode->_prev = pcur;
	newnode->_next = pHead;
	pHead->_prev = newnode;
}


void ListPrint(ListNode* pHead)
{
	ListNode* pcur = pHead->_next;
	while (pcur!= pHead)
	{
		printf("%d->", pcur->_data);
		pcur = pcur->_next;
	}
	printf("NULL\n");

}


void ListPopBack(ListNode* pHead)
{
	assert(pHead && pHead->_next != pHead);
	ListNode* pcur = pHead;
	while (pcur->_next != pHead)
	{
		pcur = pcur->_next;
	}
	pcur->_prev->_next = pHead;
	pHead->_prev = pcur->_prev;
	free(pcur);
}

void ListPushFront(ListNode* pHead, LTDataType x)
{
	assert(pHead);

	ListNode* newnode = ListBuyNode(x);
	ListNode* pcur = pHead->_next;
	newnode->_next = pcur;
	newnode->_prev = pHead;
	pHead->_next = newnode;
	pcur->_prev = newnode;
}


void ListPopFront(ListNode* pHead)
{
	assert(pHead && pHead->_next != pHead);
	ListNode* pcur = pHead->_next;
	pHead->_next = pcur->_next;
	pcur->_next->_prev = pHead;
	free(pcur);
}


ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	assert(pHead);
	ListNode* pcur = pHead->_next;
	while (pcur != pHead)
	{
		if (pcur->_data == x)
			return pcur;
		pcur = pcur->_next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* newnode = ListBuyNode(x);
	newnode ->_next = pos;
	newnode->_prev = pos->_prev;
	pos->_prev->_next = newnode;
	pos->_prev = newnode;

}


void ListErase(ListNode* pos)
{
	assert(pos);
	pos->_prev->_next = pos->_next;
	pos->_next->_prev = pos->_prev;
	free(pos);
}


void ListDestory(ListNode* pHead)
{
	assert(pHead);
	ListNode* pcur = pHead->_next;
	ListNode* next;

	while (pcur!=pHead)
	{
		next = pcur->_next;
		free(pcur);
		pcur = next;
	}
	free(pHead);
}
